﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Windows.Controls;
using System.Windows;
using System.Collections.Specialized;
using Microsoft.LightSwitch.Threading;
namespace LightSwitchApplication
{
    public partial class EmployeeTreeView
    {
        private TreeView treeView = null;
        partial void EmployeeTreeView_Created()
        {
            this.ParentEmployeeKey = 0;
            this.RootEmployees.Load();
            this.FindControl("TreeViewControl").ControlAvailable += ((o, e) =>
            {
                treeView = e.Control as TreeView;
                treeView.BorderThickness = new Thickness(0);
                if (treeView.Items.Count == 0)
                {
                    foreach (var item in this.RootEmployees)
                    {
                        TreeViewItem rootItem = new TreeViewItem() { Header = item.EmployeeName, Tag = item.EmployeeKey };
                        treeView.Items.Add(rootItem);
                    }
                    treeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(TreeViewItem_SelectedItemChanged);
                }
            });
        }

        private void TreeViewItem_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var parentItem = e.NewValue as TreeViewItem;
            this.ParentEmployeeKey = (int)parentItem.Tag;
            ///when collection is refreshed the event SelectedNodeEmployees_Changed is hooked up
            ///do not use Load method to avoid caching
            this.SelectedNodeEmployees.Refresh();
        }

        partial void SelectedNodeEmployees_Changed(NotifyCollectionChangedEventArgs e)
        {
            if (treeView != null)
            {
                Dispatchers.Main.BeginInvoke(() =>
                {
                    var parentItem = treeView.SelectedItem as TreeViewItem;
                    if (parentItem != null)
                    {
                        if (parentItem.Items.Count == 0 && this.SelectedNodeEmployees.Count() > 0)
                        {
                            foreach (var item in this.SelectedNodeEmployees) //.Where(act => act.Title != "???")
                            {
                                TreeViewItem newChildItem = new TreeViewItem() { Header = item.EmployeeName, Tag = item.EmployeeKey };
                                parentItem.Items.Add(newChildItem);
                            }
                        }
                    }
                });
            }
        }
    }
}
